package de.in.tum.msspp.Logger;

import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;



public class Compass implements SensorEventListener{
	
private Accelerometer accelerometer;
private double direction;
private float[] rotationMatrix = new float[9];
private float[] inclinationMatrix = new float[9];
private float[] eulerDegrees = new float[3];

	
	public Compass(SensorManager sensorManager, Accelerometer accelerometer){
		this.accelerometer = accelerometer;
        sensorManager.registerListener(this,
				sensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD),
				SensorManager.SENSOR_DELAY_GAME);
        direction = 0;
	}

	@Override
	public void onAccuracyChanged(Sensor arg0, int arg1) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onSensorChanged(SensorEvent event) {
		SensorManager.getRotationMatrix(rotationMatrix, inclinationMatrix, accelerometer.getXyzAcceleration(), event.values);
   		SensorManager.getOrientation(rotationMatrix, eulerDegrees);
		direction = eulerDegrees[0];
	}
	
	/**
	 * returns the current direction between -180 and 180 degrees
	 * where 0 is north, (-)180 is south, -90 is west and 90 is east
	 * @return
	 */
	public double getDirection() {
		return (direction*180/Math.PI);
	}
}
